package com.boco.pciv;

import cn.hutool.core.util.StrUtil;
import com.boco.pciv.core.interceptor.AccessLogInterceptor;
import com.boco.pciv.core.util.UploadFileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.UnsupportedEncodingException;

/**
 * Created by CC on 2017/6/13.
 * web配置
 */
@Configuration
public class PcivWebMvcConfigurer implements WebMvcConfigurer {
    //logger
    private static final Logger logger = LoggerFactory.getLogger(PcivWebMvcConfigurer.class);
//    @Bean
//    public HandlerInterceptor getAuthInterceptor(){
//        //拦截器中需要用到 Autowired 因此需要用Bean声明
//        return new RestAuthInterceptor();
//    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //日志记录拦截器
        registry.addInterceptor(new AccessLogInterceptor()).addPathPatterns("/**")
                .excludePathPatterns("/js/**")
                .excludePathPatterns("/css/**")
                .excludePathPatterns("/images/**")
                .excludePathPatterns("/assets/**")
        ;
//        registry.addInterceptor(new AuthInterceptor()).addPathPatterns("/**")
//                .excludePathPatterns("/js/**")
//                .excludePathPatterns("/css/**")
//                .excludePathPatterns("/images/**")
//                .excludePathPatterns("/assets/**");
    }
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry){
        String basePath="";
        try {
            basePath = UploadFileUtil.getBasePath();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (StrUtil.isNotBlank(basePath)){
            logger.info("add resource:{}",basePath);
            registry.addResourceHandler(basePath).addResourceLocations("classpath:/static/");
        }
//        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")//设置允许跨域的路径
                .allowedOrigins("*")//设置允许跨域请求的域名
                .allowCredentials(true)//是否允许证书 不再默认开启
                .allowedMethods("GET", "POST", "PUT", "DELETE")//设置允许的方法
                .maxAge(3600);//跨域允许时间
    }
}
